import { getGantPopupContainer } from '@/utils/utils';
import { Selector } from 'gantd';
import type { WithBasicProps } from 'gantd/lib/compose/withbasic';
import type { SelectValue } from 'gantd/lib/selector';
import React, { useCallback, useMemo } from 'react';
import request from '@/utils/request';

export type CodeListValue = SelectValue | undefined;
type BS = string | boolean;
const boolMap = new Map<BS, BS>([
  ['false', false],
  ['true', true],
  [false, 'false'],
  [true, 'true'],
]);

function formatBoolValue(value: BS | BS[]): CodeListValue {
  function formatBoolValueInner(value: BS): BS {
    if (boolMap.has(value)) {
      return boolMap.get(value) as BS;
    }
    return value;
  }

  if (Array.isArray(value)) {
    return value.map(formatBoolValueInner) as CodeListValue;
  }
  return formatBoolValueInner(value as BS);
}

export interface CodeListProps extends WithBasicProps {
  type: string;
  value: BS;
  cacheKey?: string;
  multiple?: boolean;
  mode?: string;
  onChange?: (v: CodeListValue) => void;
  // onSave?: (id: string, value: CodeListValue, cb: Function) => void,
  filterFn?: (data: any) => any;
  departFilterFn?: (data: any, theStr: any) => any;
  allowEdit?: boolean;
}

type CodeListIf = {
  type: string;
  [key: string]: any;
};

const CodeList = React.forwardRef<HTMLDivElement, CodeListProps>((props: CodeListIf, ref) => {
  const {
    type,
    value,
    onChange,
    onSave,
    filterFn,
    departFilterFn,
    cacheKey,
    placeholder = tr('请选择'),
    ...prop
  } = props;
  const query = useCallback(
    () =>
      request
        .post('/pjDepartmentProduct/findCanEditPersonTypeObj', {
          data: { value: type },
          serviceId: 'project',
        })
        .then((data) => {
          return data;
        }),
    [filterFn, type],
  );

  const boolValue = useMemo(() => formatBoolValue(value), [value]);

  const onValueChange = useCallback((val: CodeListValue) => {
    if (onChange) onChange(formatBoolValue(val as BS));
  }, []);

  const save = useCallback((id, val, cb) => {
    if (onSave) onSave(id, formatBoolValue(val), cb);
  }, []);

  const selectorId = useMemo(() => {
    let str = `codelistdepart-${type}`;
    if (cacheKey) str += `-${cacheKey}`;
    return str;
  }, [cacheKey, type]);
  return (
    <div ref={ref}>
      <Selector
        getPopupContainer={getGantPopupContainer}
        useStorage={false}
        selectorId={selectorId}
        query={query}
        valueProp="codeItemValue"
        labelProp="codeItemName"
        value={boolValue}
        onChange={onValueChange}
        onSave={save}
        placeholder={placeholder}
        {...prop}
      />
    </div>
  );
});

export default CodeList;
